/**
 * Copyright 2012 Evernote Corporation.
 *
 * Shared header functionality.
 */
var Evernote;

define(["jquery", "common", "domReady!"], function($, common) {
  if (Evernote == null) {
    Evernote = {};
  }

  var chatbutton = $("#chat-button");
  var gearArrow = $(".gear-dropdown-arrow");
  var userIcon = $(".gear-bbox");
  var gearDropdown = $(".gear-dropdown");
  var gearmenubutton = $(".gear-dropdown-bbox");
  var gearmenuuser = $(".gear-dropdown-user");
  var gearmenu = $(".gear-dropdown-menu");
  var gearicon = $(".gear-dropdown-gear");
  var logoutButton = $(".logout", gearDropdown);

  /*
   * Generates a function to set the max-width on the username
   * element, given the current window width.
   *
   * Precondition: The header does not have `display: none`.
   */
  var getTruncateUsernameFunction = function() {
    // Get the left width, depending on whether we are showing
    // the normal nav bar or the business logo header only.
    var leftWidth = $('.nav').length
        ? $('.left').outerWidth(true) : $('.evernote-logo').outerWidth(true);

    // Get the right width, minus the username text's width.
    var extraPadding = 8;
    var rightExcessWidth = gearDropdown.width() + extraPadding
        - gearmenuuser.width();

    return function() {
      var maxTextWidth = $(window).width() - leftWidth - rightExcessWidth;
      gearmenuuser.css('max-width', maxTextWidth);
    };
  };

  /* Hook up chat link */
  chatbutton.click(function(event) {
    var link = chatbutton.attr("href");
    event.preventDefault();
    if (link !== "") {
      window.open(link, "_blank", "width=600,height=800");
    }
  });

  var onMenuClick = function(event) {
    event.preventDefault();
    event.stopPropagation();
    toggleMenu();
  };

  /* Turn gear menu on/off by clicking your username / gear icon */
  var toggleMenu = function() {
    gearmenu.toggle();
    gearmenubutton.toggleClass("active");
    gearicon.toggleClass("active");
    gearDropdown.toggleClass("no-highlight");
  };

  common.addClickOut(gearmenu, toggleMenu);
  common.blockDoubleClick(logoutButton);

  /* Hook up menu button to toggle menu */
  gearmenubutton.click(onMenuClick);
  gearmenuuser.click(onMenuClick);
  userIcon.click(onMenuClick);
  gearArrow.click(onMenuClick);

  // Truncate username if too long - update on window resize.
  $(window).resize(getTruncateUsernameFunction());
  $(window).resize();
});
